package gwtgaetools.client;

import gwtgaetools.client.listeners.Listener;
import gwtgaetools.shared.model.BaseObject2;
import gwtgaetools.shared.model.ObjectManager2;

import java.util.ArrayList;

public class OMList2<T extends BaseObject2<T>, M extends ObjectManager2<T, M>>
	extends BasicList<M> {

    /**
	 * 
	 */
    private static final long serialVersionUID = 1L;

    public OMList2() {
    }

    public OMList2(ArrayList<M> i) {
	super(i);
    }

    @Override
    public boolean add(final M t) {
	boolean b = false;
	if (t.index() != null) {
	    int i = findIndex(t);

	    super.add(i, t);

	    b = true;

	    t.index().listeners.add(new Listener<ItemManager<Integer>>() {
		@Override
		public void observe(ItemManager<Integer> it) {
		    updateIndex(t, findIndex(t), indexOf(t));
		}
	    });
	} else {
	    b = super.add(t);
	}
	t.deleteListeners.add(this);
	return b;
    }

    @Override
    public void add(int index, M t) {
	super.add(index, t);
	t.deleteListeners.add(this);
    }

    @Override
    public M getById(String id) {
	for (M t : this) {
	    if (t.sameAs(id))
		return t;
	}
	return null;
    }

    public int indexOf(M in) {
	for (int i = 0; i < size(); i++) {
	    M t = get(i);
	    if (t.sameAs(in))
		return i;
	}
	return -1;
    }

    private int findIndex(M t) {
	int i = 0;
	boolean passObject = false;
	while (i < size()) {
	    if (t.sameAs(get(i)))
		passObject = true;
	    else if (t.index().getItem() < get(i).index().getItem())
		break;
	    i++;
	}
	if (passObject)
	    i--;
	return i;
    }

}
